<template>
  <a-spin :spinning="confirmLoading">
    <!-- 主表单区域 -->
    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="业务员" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="operator"
              ref="operatorFmi">
              <j-select-user-by-dep v-model="model.operator" :multi="false" @change="onOperatorChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="单据编号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="billNo">
              <a-input placeholder="请输入" v-model="model.billNo" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据日期" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="billDate">
              <!--JDate 清空或键盘删空，即使输入了合法日期，必填校验提示仍一直显示，故设置allowClear=false和inputReadOnly=true-->
              <j-date v-model="model.billDate" :readOnly="disabled" placeholder="请选择日期" style="width: 100%"
                :allowClear="false" :inputReadOnly="true" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="联系人" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.contact" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="联系电话" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.phone" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="电子邮件" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.email" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="订单总金额" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.totalAmt" :disabled="!disabled" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="币种" :labelCol="labelCol" :wrapperCol="wrapperCol3" prop="currency">
              <j-dict-select-tag v-model="model.currency" dictCode="bas_currency,name,code" placeholder="请选择"
                :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="订单总付款金额" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.totalPayAmount" :disabled="!disabled" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol3" prop="customerId">
              <j-search-select-tag v-model="model.customerId" :async="true" dict="bas_customer,name,id"
                placeholder="请选择" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="附件" :labelCol="labelCol1" :wrapperCol="wrapperCol3" prop="attachment">
              <j-upload v-model="model.attachment" :disabled="disabled"></j-upload>
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- 子表单区域 -->
        <a-tabs v-model="activeKey" @change="handleChangeTabs">
          <a-tab-pane tab="供应商列表" :key="refKeys[0]" :forceRender="true">
            <j-vxe-table keep-source :ref="refKeys[0]" :columns="supplierTable.columns" :toolbar="!disabled"
              :dataSource="supplierTable.dataSource" :maxHeight="300" :rowNumber="false" :rowSelection="!disabled"
              :resizable="true" :edit-config="{ trigger: 'click', mode: 'row', showIcon: false }"
              @edit-actived="({ row }) => setSupplierUnitOptions(row, $refs.supplierTable)" @added="onInEntryAdded" />
            <!-- @valueChange="onEntryValueChange" /> -->
          </a-tab-pane>
          <a-tab-pane tab="产品" :key="refKeys[1]" :forceRender="true">
            <j-vxe-table keep-source :ref="refKeys[1]" :columns="productTable.columns"
              :dataSource="productTable.dataSource" :maxHeight="300" :rowNumber="false" :rowSelection="!disabled"
              :toolbar="!disabled" :resizable="true" :edit-config="{ trigger: 'click', mode: 'row', showIcon: false }"
              @edit-actived="({ row }) => setProductUnitOptions(row, $refs.productTable)" @added="onInEntryAdded"
              @valueChange="onEntryValueChange" />
          </a-tab-pane>


        </a-tabs>
        <!-- <bill-footer ref="billFooter" :model="model" :disabled="disabled" :action="action" /> -->
      </a-form-model>
    </div>

  </a-spin>
</template>

<script>

import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { OrderFormMixin, OrderFormGridMixin } from '../../common/mixins/OrderFormMixin'
import { OrderVxeTableMixin } from '../../common/mixins/OrderVxeTableMixin'
// import BillFooter from "../../common/components/BillFooter";
import VxeTableColumnsSetter from "../../common/components/VxeTableColumnsSetter";
import JVxeCustomUploadCell from '@/components/jeecg/JVxeTable/components/cells/JVxeCustomUploadCell.vue';
export default {
  id: " ",
  name: 'OrderScaleForm',
  mixins: [JVxeTableModelMixin, OrderFormMixin, OrderFormGridMixin, OrderVxeTableMixin],
  components: { VxeTableColumnsSetter },

  data() {
    return {
      model: {
        //设置初始值的属性、程序赋值的响应式属性
        billNo: " ",
        disabled: true,
        billDate: null,
        customerId: " ",
        contact: " ",
        phone: " ",
        email: " ",
        opDept: " ",
        operator: " ",
        deliveryMethod: " ",
        deliveryPlace: " ",
        deliveryTime: " ",
        transportMethod: " ",
        paymentMethod: " ",
        settleMethod: " ",
        settleTime: " ",
        currency: " ",
        exchangeRate: null,
        settledAmt: null,
        payedAmount: null,
        attachment: null,
        remark: " ",
        approver: " ",
        bpmiInstanceId: " ",
        approvalResultType: " ",
        approvalRemark: " ",
        isEffective: null,
        effectiveTime: " ",
        isClosed: null,
        isVoided: null,
        sysOrgCode: " ",
        createBy: " ",
        createTime: " ",
        updateBy: " ",
        updateTime: " ",
        version: 0,

        supplierList: [
          {
            id: " ",
            salOrderWrId: " ",
            supplierId: " ",
            contractNo: " ",
            remark: " ",
            settleFlag: 0,
            totalAmount: 0,
            attachName: " ",
            attachUrl: " ",
            createBy: " ",
            createTime: " ",
            updateBy: " ",
            updateTime: " "
          }
        ],
        productList: [
          {
            id: " ",
            salOrderWrId: " ",
            productId: " ",
            supplierId: " ",
            buyUnitAmount: 0,
            sealUnitAmount: 0,
            qty: 0,
            createBy: " ",
            createTime: " ",
            updateBy: " ",
            updateTime: " "
          }
        ]

      },
      // 1. 新增：专门存储下拉选项数据（不影响表格行数）
      supplierOptionsTable: { // 供应商下拉选项数据
        loading: false,
        dataSource: [],
        url: { list: '/base/basSupplier/list' }
      },
      productOptionsTable: { // 产品下拉选项数据
        loading: false,
        dataSource: [],
        url: { list: '/base/basProduct/list' }
      },
      validatorRules: {},

      entryNoStep: 10,
      addDefaultRowNum: 1,
      refKeys: ['supplierTable', 'productTable'],
      tableKeys: ['supplierTable', 'productTable'],
      activeKey: 'supplierTable',

      // 供应商列表
      supplierTable: {
        loading: false,
        dataSource: [],
        url: {
          list: '/wr/salOrderWr/queryById'
        },
        columns: [

          {
            title: '供应商',
            key: 'supplierId',
            type: JVXETypes.selectSearch,
            options: [],
            dictCode: "bas_supplier,name,id",
            width: "200px",
            fixed: 'left',
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '产品',
            key: 'productId',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '合同号',
            key: 'contractNo',
            type: JVXETypes.input,
            width: "300px",
            align: "left",
            formatter: this.formatQty,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
            // statistics: ['sum'],
          },
          /*  {
             title: '销售订单ID',
             key: 'salOrderWrId',
             type: JVXETypes.input,
             width: "300px",
             align: "left",
             formatter: this.formatQty,
             placeholder: '请输入',
             defaultValue: '',
             validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
             // statistics: ['sum'],
           }, */
          {
            title: '上传',
            key: 'upload',
            type: JVXETypes.tableupload,
            visible: true, // 强制显示列
            width: '180px', // 宽度足够显示按钮（至少100px以上）
            // 确保没有hidden: true或其他隐藏配置
            // hidden: true, // 若有这行，会隐藏列
            btnText: '点击上传', // 按钮文字不为空
            token: true,
            responseName: 'message',
            action: window._CONFIG['domianURL'] + '/sys/common/upload'
          },
          // 显示attachName和attachUrl的列（可选，用于验证）
          {
            title: '附件名',
            key: 'attachName',
            type: JVXETypes.input,
            width: '200px',
            readOnly: true // 只读，避免手动修改
          },
          {
            title: '附件地址',
            key: 'attachUrl',
            type: JVXETypes.input,
            width: '300px',
            readOnly: true
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: "160px",
            defaultValue: '',
          },
          {
            title: '供应商总采购价',
            key: 'totalAmount',
            type: JVXETypes.input,
            width: "160px",
            disabled: true,
            defaultValue: '',
          },
          {
            title: '物料是否充足',
            key: 'ismaterial',
            type: JVXETypes.dictTag,
            width: "100px",
            align: "left",
            placeholder: '请输入',
            defaultValue: '1',
            // validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
            // statistics: ['sum'],
          },
          {
               title: '是否结算',
               key: 'settleFlag',
               type: JVXETypes.dictTag, // 字典编码（0=否，1=是）
               width: "100px",
               align: "left",
               placeholder: '请选择'
             }, 
        ]
      },
      productTable: {
        loading: false,
        dataSource: [],
        url: {
          list: '/wr/salOrderWr/queryById'
        },
        columns: [
          {
            title: '产品',
            key: 'productId',
            type: JVXETypes.selectSearch,
            options: [],
            dictCode: "bas_product,name,id",
            width: "300px",
            fixed: 'left',
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '采购单价',
            key: 'buyUnitAmount',
            type: JVXETypes.inputNumber,
            width: "200px",
            align: "left",
            formatter: this.formatQty,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
            // statistics: ['sum'],
          },
          {
            title: '销售单价',
            key: 'sealUnitAmount',
            type: JVXETypes.inputNumber,
            width: "200px",
            align: "left",
            formatter: this.formatQty,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
            // statistics: ['sum'],
          },
          {
            title: '数量',
            key: 'qty',
            type: JVXETypes.inputNumber,
            width: "200px",
            align: "left",
            formatter: this.formatQty,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
            // statistics: ['sum'],
          },
          {
            title: '供应商',
            key: 'supplierId',
            type: JVXETypes.selectSearch,
            options: [],
            dictCode: "bas_supplier,name,id",
            width: "300px",
            fixed: 'left',
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
        ]
      },
      url: {

        add: "/wr/salOrderWr/add",
        edit: "/wr/salOrderWr/edit",
        /*         check: "/stock/stkIo/check",
                ebpm: "/stock/stkIo/bpm/end",
                execute: "/stock/stkIo/execute",
                void: "/stock/stkIo/void", */
      },

    }
  },

  created() {

    console.log('自定义上传组件是否存在:', JVxeCustomUploadCell);
    // 等待物料options加载完成
    // this.initMaterialRelated();
    this.initSupplierRelated();
    this.initProductRelated();
    console.log('created执行');

  },
  methods: {
    addBefore() {
      this.supplierTable.dataSource = [];
    },

    addAfter() {
      this.$refs.billHeader.fillBillNo(
        'stk_qtrk_bill_no',
        (billNo) => {
          this.$nextTick(() => {
            //异步执行原因，初始空白行增加时，billNo可能还未获得！
            let rows = this.$refs.supplierTable.getNewDataWithId();
            for (let row of rows) {
              this.$refs.supplierTable.setValues([{ rowKey: row.id, values: { batchNo: billNo + '-' + row.entryNo } }]);
            }
          })
        });
    },

    getAllTable() {
      console.log('getAllTable执行');
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      console.log('values', values);
      return Promise.all(values)
    },

    editAfter() {
      setTimeout(() => {
        if (this.model.id) {
          let params = { id: this.model.id };
          console.log('获取表格数据开始========================>');

          this.requestSubTableData(this.supplierTable.url.list, params, this.supplierTable, 'supplierList', () => {
            console.log('明细数据加载结果：', this.supplierTable.dataSource); // 新增日志
            // 检查明细数据是否为空a
            if (!this.supplierTable.dataSource || this.supplierTable.dataSource.length === 0) {
              console.warn('供应商明细数据为空，可能接口返回空或参数错误');
            }
          });
          this.requestSubTableData(this.productTable.url.list, params, this.productTable, 'productList', () => {
            console.log('产品明细数据加载结果：', this.productTable.dataSource); // 新增日志
            // 检查明细数据是否为空a
            if (!this.productTable.dataSource || this.productTable.dataSource.length === 0) {
              console.warn('明细数据为空，可能接口返回空或参数错误');
            }
          });
        }
      }, 1500);

    },

    classifyIntoFormData(allValues) {
      console.log('分类表单数据', allValues);
      console.log('allValues.tablesValue结构：', allValues.tablesValue); // 确认数据结构

      let main = Object.assign(this.model, allValues.formValue);
      // 用 && 替代 ?.，确保前面的属性存在再访问tableData
      const supplierTableData = allValues.tablesValue && allValues.tablesValue[0] && allValues.tablesValue[0].tableData || [];
      const productTableData = allValues.tablesValue && allValues.tablesValue[1] && allValues.tablesValue[1].tableData || [];

      return {
        ...main, // 展开主表数据
        supplierList: supplierTableData, // 供应商表格数据（对应tablesValue[0]）
        productList: productTableData   // 产品表格数据（对应tablesValue[1]）
      };
    },
    //当行内数据发生改变的时候，其余数据联动更新
    onEntryValueChange(event) {
      const { type, value, oldValue, row, column, target, isSetValues } = event;
      if (value === oldValue || isSetValues) return;

      switch (column.property) {
        case "entryNo": //联动：分录号 --> 批次
          if (!row.batchNo || row.batchNo === this.model.billNo + "-" + oldValue) {
            target.setValues([{ rowKey: row.id, values: { batchNo: this.model.billNo + "-" + value } }]);
          }
          break;
        case "materialId":
          this.handleMaterialChange(row, target);
          break;
        case "unitId":
          if (!oldValue || oldValue.length === 0 || !value || value.length === 0) break;
          let rate = this.getUnitRate(row.materialId, oldValue, value);
          if (!rate)
            target.setValues([{ rowKey: row.id, values: { unitId: oldValue } }]);
          else
            target.setValues([{
              rowKey: row.id,
              values: {
                qty: (row.qty * rate).toFixed(3),
                price: (row.price / rate).toFixed(2)
              }
            }]);
          break;
        case "qty":
        case "price":
          target.setValues([{
            rowKey: row.id,
            values: { cost: (row.qty * row.price).toFixed(2) }
          }]);
          break;
      }
    },

    costValidator({ cellValue, row, column }, callback, target) {
      const v = Number(cellValue);
      if (isNaN(v)) {
        callback();
        return;
      }

      let diff = v - Number((row.qty * row.price).toFixed(2));
      if (diff < -0.01001 || diff > 0.01001) {
        callback(false, '${title}的输入值与计算值相差超过0.01元！');
      } else {
        callback(true); //true：通过验证
      }
    },

  }
}
</script>

<style lang="less" scoped>
@import "../../common/less/BillForm.less";
</style>
